package com.bestv.search.engine.servlet;

import com.bestv.search.engine.command.HitCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * @author Michael Wang
 */
public class HitServlet extends HttpServlet {
    private static final long serialVersionUID = 8319468779324549354L;
    protected final Log log = LogFactory.getLog(getClass());
    private HitCommand hitCommand;

    public HitServlet() {
        super();
    }

    public void init() throws ServletException {
        super.init();
        ServletContext application = getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
        hitCommand = (HitCommand) wac.getBean("hit");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String hStr = URLDecoder.decode(req.getParameter("q"), "UTF-8");
        doExcute(hStr);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String hStr = URLDecoder.decode(req.getParameter("q"), "UTF-8");
        doExcute(hStr);
    }

    private void doExcute(String hReq) throws IOException {
        hReq = new String(hReq.getBytes("iso-8859-1"), "utf-8");
        log.debug("hitStr: " + hReq);
        SAXReader reader = new SAXReader();
        Document doc = null;
        InputStream xmlInputStream = new ByteArrayInputStream(hReq.getBytes("UTF-8"));
        try {
            doc = reader.read(xmlInputStream);
        } catch (Exception e) {
            return;
        } finally {
            xmlInputStream.close();
        }
        String cmd = doc.selectSingleNode("/request/cmd").getText();
        if (!cmd.equalsIgnoreCase("hit")) {
            log.error("It doesn't match the hit command.");
            log.error(doc.asXML());
            return;
        }
        hitCommand.hit(doc);
    }
}
